<?php
namespace Admin\Model;
use Think\Model;
class OrderModel extends Model 
{
/*	protected $insertFields = array('shr_name','shr_tel','shr_province','shr_city','shr_area','shr_address');
	protected $_validate = array(
		array('shr_name', 'require', '收货人姓名不能为空！', 1, 'regex', 3),

		array('shr_tel', 'require', '收货人电话不能为空！', 1, 'regex', 3),

		array('shr_province', 'require', '收货人省份不能为空！', 1, 'regex', 3),

		array('shr_city', 'require', '收货人城市不能为空！', 1, 'regex', 3),

		array('shr_area', 'require', '收货人地区不能为空！', 1, 'regex', 3),

		array('shr_address', 'require', '收货人地址不能为空！', 1, 'regex', 3),
	);*/
    protected $insertFields = array('inv_payee','inv_content');

    /**得到新订单号**/
    static public function get_order_sn(){
        mt_srand((double) microtime() * 1000000);
        return date('Ymd').str_pad(mt_rand(1,99999),5,'0',STR_PAD_LEFT);
    }

    /**后台订单**/
    public function lst($pageSize = 20)
    {
        /************************************* 搜索 ****************************************/
        $where = array();
        if($pay_status = I('get.pay_status')){
            $where['pay_status'] = array('eq',$pay_status);
        }

        if($post_status = I('get.post_status')){
            if($post_status == 1){
                $where['post_status'] = array('eq',0);
                $where['pay_status'] = array('eq','Y');
            } else {
                $where['post_status'] = array('eq',$post_status);
            }
        }

        //收货人
        if($shr_name = I('get.shr_name')){
            $where['shr_name'] = array('like',"%$shr_name%");
        }
        //电话
        if($shr_tel = I('get.shr_tel')){
            $where['shr_tel'] = array('like',"%$shr_tel%");
        }
        //快递单号
        if($post_number = I('get.post_number')){
            $where['post_number'] = array('like',"%".trim($post_number)."%");
        }
        //下单时间
        if(!empty(I('get.o_fa')) && !empty(I('get.o_ta'))){
            $min = strtotime(I('get.o_fa'));
            $max = strtotime(I('get.o_ta'));
            $where['add_time'] = array(array('egt',$min),array('elt',$max));
        }
        //支付时间
        if(!empty(I('get.p_fa')) && !empty(I('get.p_ta'))){
            $min = strtotime(I('get.p_fa'));
            $max = strtotime(I('get.p_ta'));
            $where['pay_time'] = array(array('egt',$min),array('elt',$max));
        }
        //总价格
        if(!empty(I('get.min_price')) && !empty(I('get.max_price'))){
            $where['total_price'] = array(array('egt',I('get.min_price')),array('elt',I('get.max_price')));
        }


        /************************************* 翻页 ****************************************/
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/
        $data['data'] = $this->alias('a')
            ->where($where)
            ->group('a.id')
            ->order('a.addtime DESC')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        return $data;
    }

    /**前台订单**/
	public function search($pageSize = 20)
	{
        /************************************* 搜索 ****************************************/
        $memberId = session('m_id');
        $where['member_id'] = array('eq',$memberId);
        $noPayCount = $this->where(array(
            'member_id' => array('eq',$memberId),
            'pay_status' => array('eq','否'),
        ))->count;
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		$data['data'] = $this->alias('a')
            ->field('a.*,GROUP_CONCAT(DISTINCT c.sm_logo) logo')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON a.id=b.order_id
                    LEFT JOIN __GOODS__ c ON b.goods_id=c.id')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $data['noPayCount'] = $noPayCount;
		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, &$option)
	{
	    $memberId = session('m_id');
        /**下单之前的检查**/
        //是否登录
        if(!$memberId){
            $this->error = "请先登录！";
            return false;
        }
        //购物车中是否有商品
        $cartModel = D('Cart');
        $option['goods'] = $goods = $cartModel->cartList();
        if(!$goods){
            $this->error = '购物车中无商品，无法下单！';
            return false;
        }

        //读取库存之前加锁
        $this->fp = fopen('./order.lock');
        flock($this->fp,LOCK_EX);

        //循环购物车中的商品检查库存量并计算商品总价
        $gnModel = D('goodsNumber');
        $total_price = 0;
        foreach ($goods as $k => $v){
            //检查库存量
            $gnNumber = $gnModel->field('goods_number')->where(array(
                'goods_id' => array('eq',$v['goods_id']),
                'goods_attr_id' => array('eq',$v['goods_attr_id']),
            ))->find();

            if($gnNumber['goods_number'] < $v['goods_number']){
                $this->error = '下单失败，商品：<strong>'.$v['goods_name'].'</strong>库存量不足！';
                return false;
            }
            //统计总价
            $total_price += $v['price'] * $v['goods_number'] + $yf;
        }

        //收货地址
        $address_id = I('post.address_id',0);
        if($address_id){
            $addressModel = D('Admin/UserAddress');
            $addressData = $addressModel->relation(true)->find($address_id);
            $data['shr_name'] = $addressData['consignee'];
            $data['shr_tel'] = $addressData['mobile'];
            $data['shr_province'] = $addressData['province']['region_name'];
            $data['shr_city'] = $addressData['city']['region_name'];
            $data['shr_area'] = $addressData['district']['region_name'];
            $data['shr_address'] = $addressData['address'];


        } else {
            $this->error = "请选择收货地址！";
            return false;
        }

        //送货方式
        $shipping_id = I('post.shipping_id',0);
        $config_option = I('post.config_option');
        if($shipping_id){
            $shippingModel = D('Admin/Shipping');
            $shippingData = $shippingModel->find($shipping_id);
            $data['shipping_id'] = $shippingData['shipping_id'];
            $data['shipping_name'] = $shippingData['shipping_name'].' '.$config_option[$shipping_id];
            $total_price += $shippingData['insure'];
        } else {
            $this->error = "请选择送货方式！";
            return false;
        }

        $data['member_id'] = $memberId;
        $data['addtime'] = time();
        $data['total_price'] = $total_price;
        $data['order_sn'] = self::get_order_sn();

        //发票信息
        if($data['inv_payee'] == 'personal'){
            $data['inv_payee'] = '个人';
        } elseif ($data['inv_payee'] == 'company'){
            $data['inv_payee'] = '单位：'.I('post.company_name');
        }

        $this->startTrans();


	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
	}
	// 删除前
	protected function _before_delete($option)
	{
	    $id = $option['where']['id'];
	    //删除订单商品
        $ogModel = D('order_goods');
        $ogModel ->where(array(
            'order_id' => array('eq',$id),
        ))->delete();

	}
	//添加后
    public function _after_insert($data,$option){
        //从$option中取出购物车商品并循环插入到订单商品表中且减少库存
        $ogModel = D('order_goods');
        $gnModel = D('goods_number');
        foreach($option['goods'] as $k => $v){
            $ret = $ogModel->add(array(
                'order_id' => $data['id'],
                'goods_id' => $v['goods_id'],
                'goods_attr_id' => $v['goods_attr_id'],
                'goods_number' => $v['goods_number'],
                'price' => $v['price'],
            ));
            if(!$ret){
                $this->rollback();
                return false;
            }
            //减少库存
            $ret = $gnModel->where(array(
                'goods_id' => array('eq',$v['goods_id']),
                'goods_attr_id' => array('eq',$v['goods_attr_id']),
            ))->setDec('goods_number',$v['goods_number']);
            if($ret == false){
                $this->rollback();
                return false;
            }
        }
        //所有操作都成功提交事务
        $this->commit();
        //释放锁
        flock($this->fp,LOCK_EX);
        fclose($this->fp);
        //清空购物车
        $cartModel = D('Cart');
        $cartModel->clear();
    }

    //设置已支付的状态
    public function setPaid($orderId){
        //更新订单的支付状态
        $this->where(array(
            'id' => array('eq',$orderId),
        ))->save(array(
            'pay_status' => '是',
            'pay_time' => time(),
        ));
        //更新会员积分
        $tp = $this->field('total_price,member_id')->find($orderId);
        $memberModel = M('member');
        $memberModel->where(array(
            'id' => array('eq',$tp['member_id']),
        ))->setInc('jifen',$tp['total_price']);
    }

    //取出一个订单详情
    public function getDetail($orderId){
        $goodsModel = D('Admin/Goods');
        $goodsAttrModel = D('Admin/GoodsAttr');
        $orderGoodsModel = D('Admin/OrderGoods');
        $orderData = $this->find($orderId);
        $orderData['goods_list'] = $orderGoodsModel->where(array('order_id'=>$orderId))->select();
        foreach ($orderData['goods_list'] as $k=>&$v){
            $goodsData = $goodsModel->field('goods_name,sm_logo')->find($v['goods_id']);
            $v['goods_name'] = $goodsData['goods_name'];
            $v['sm_logo'] = $goodsData['sm_logo'];
            if($v['goods_attr_id']){
                $v['gaData'] = $goodsAttrModel->alias('a')
                    ->field('a.attr_value,b.attr_name')
                    ->join('LEFT JOIN __ATTRIBUTE__ b ON a.attr_id=b.id')
                    ->where(array(
                        'a.id' => array('IN',$v['goods_attr_id'])
                    ))->select();
            }
        }
        return $orderData;
    }
}